﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ARR.Entities.ComponentModel;
using ARR.Shared;
using System.Reflection;

namespace ARR.Entities.Validation.Common
{
    [Serializable]
    public class StringLength : ValidationBase
    {
        int maxStringLength;

        public StringLength(string propertyName, int maxLength, string displayName = null) : base(propertyName, null)
        {
            string fieldName = displayName == null ? propertyName : displayName;
            base.ErrorMessage = string.Format(Errors.StringLengthValidation, fieldName, maxLength);

            this.maxStringLength = maxLength;
        }

        public override bool Validate(ValidatableEntity entity)
        {
            PropertyInfo pi = entity.GetType().GetProperty(this.PropertyName);
            if (pi == null)
                throw new Exception(string.Format("The Property '{0}' is not a valid property name", this.PropertyName));
            object value = pi.GetValue(entity, null);

            if (pi.PropertyType == typeof(string))
            {
                return value == null || string.IsNullOrEmpty(value.ToString()) || value.ToString().Length <= maxStringLength;
            }

            throw new Exception(string.Format("The StringLength validation is applicable only to string fields."));
        }
    }
}
